import { handler, random } from "./tools.js";
export default class _2048 {
  constructor() {
    this.game = document.querySelector(".game");
    this.body = document.body;
    this.lists = this.game.querySelectorAll("div");
    this.color = {
      0: "#fff",
      2: "#0f0",
      4: "#00ccff",
      8: "#ff9900",
      16: "#00cc66",
      32: "#ffcccc",
      64: "#ff33ff",
      128: "#0066cc",
      256: "#6633cc",
      512: "#ff0099",
      1024: "#990033",
      2048: "#6600ff",
      4096: "#cc0066",
    };
    this.numsArr;
  }
  init() {
    this.numsArr = Array.from({ length: 4 }, (item) => new Array(4).fill(0));
    this.bindEvent();
    this.render();
  }
  bindEvent() {
    this.body.addEventListener("keyup", this.keyupEvent.bind(this), false);
  }
  //键盘按下事件
  keyupEvent(ev) {
    let code = ev.keyCode;
    if (![37, 38, 39, 40].includes(code)) return;
    this.numsArr = handler[code](this.numsArr);
    //渲染数据
    this.renderNum(this.numsArr);
  }
  /* isOver(arr1, arr2) {
    //每个方向都检测 是否数组没有变化了 说明结束了
    return [37, 38, 39, 40].every((code) => {
      arr1 = handler[code](arr2);
      return [].concat(arr1).join("") === [].concat(arr2).join("");
    });
  } */
  //这个只有一个数据需要渲染
  render() {
    this.renderNum();
  }
  renderNum(arr = this.numsArr) {
    // 在0位置随机添加两个2
    random(arr);
    this.lists.forEach((div, i) => {
      let x = ~~(i / 4),
        y = i % 4;
      div.innerText = arr[x][y];
      div.style.backgroundColor = this.color[arr[x][y]];
    });
  }
}
